import { extend, RequestOptionsInit } from 'umi-request'
import { message, notification } from 'ant-design-vue'

const request = extend({
  // prefix: "/api/v1",
  // suffix: ".json",
  // timeout: 1000,
  // headers: {
  //   "Content-Type": "multipart/form-data"
  // },
  // params: {
  //   token: "xxx" // 所有请求默认带上 token 参数
  // },
  errorHandler: function (_error) {
    /* 异常处理 */
  }
})

request.interceptors.request.use((_url, options: RequestOptionsInit) => {
  const requestUrl = process.env.VUE_APP_BASE_API
  return {
    url: `${requestUrl}`,
    options: { ...options, interceptors: true }
  }
})
// response拦截器, 处理response
request.interceptors.response.use(
  // @ts-ignore
  async (response, _options: RequestOptionsInit) => {
    if (response.status === 200) {
      // if (options.responseType === 'blob') {
      //   const disposition = response.headers.get('content-disposition')
      //   if (disposition) {
      //     const splitDis = disposition.split(';')
      //     if (splitDis[0] === 'attachment') {
      //       const fileNameDefault = splitDis[1].split('filename=')[1]
      //       const fileNameUnicode = disposition.split('filename*=')[1]
      //       const _filename = fileNameUnicode
      //         ? decodeURIComponent(fileNameUnicode.split("''")[1])
      //         : fileNameDefault
      //       response
      //         .clone()
      //         .blob()
      //         .then((_blob) => {
      //           // 触发下载事件
      //           // saveAs(_blob, filename)
      //         })
      //     }
      //   }
      //   return response
      // }
      try {
        const res = await response.clone().json()

        if (!res.success) {
          notification.error({
            message: res.message || 'Error',
            duration: 5
          })
          // @ts-ignore
          return new Promise<Response>((resolve, reject) => {
            reject(response)
          })
        } else {
          return response
        }
      } catch (error) {
        switch (response.status as number) {
          case 403:
            message.error('接口跑丢了!')
            break
          case 404:
            message.error('接口错误')
            break
          case 401:
            return response
          case 500:
            message.error('接口错误')
            break
          default:
            const data = await response.clone().json()
            if (data.error.message) {
              message.error(data.error.message)
            }
        }
        // @ts-ignore
        return new Promise<Response>((resolve, reject) => {
          reject(response)
        })
      }
    }
    // @ts-ignore
    return new Promise<Response>((resolve, reject) => {
      reject()
    })
  }
)

export default request
